require "net/http"
require "data/Data"
require "set"

class ExperimentalData
  DATA_URL="http://people.cs.ubc.ca/~taosu/tacscreen/vkey/service.php?task=getall"
  
  attr_reader :group_by_uid, :group_by_layer, :group_by_set
  
  def initialize
    @group_by_uid = {}
    @group_by_layer = {}
    @group_by_set = {}
      
    @layer_map = {}
    @set_map = {}  
    _getData        
  end
    
  
  def get_layer(uid)
    return @layer_map[uid]
  end
  
  def get_sets(uid)
    return @set_map[uid].to_a().sort
  end
  
   
  private
  
  #Download the data from the web
  def _getData
    @group_by_uid = {}
    @group_by_layer = {}
    @group_by_set = {}

    resp = Net::HTTP.get_response(URI.parse(DATA_URL))
    resp.body.each do |s|
      
      # Skip if the phrase is skipped
      begin
        e = Entry.new(s)
        rescue
          next
      end  
      
      #Data correction
      next if e.uid <100
      next if e.uid == 902 #William
      next if e.uid == 501 #subject 501 and 502 are the same, due to some data entry problem 
      next if e.uid == 504 #subject 504 is the one who left the experiment due to data entry problem.
      next if e.uid == 109 # this is Tao
      
      #next if e.uid == 401 # subject too old
                  
      #initialize if nil
      @group_by_uid[e.uid] ||= []
      @group_by_layer[e.layer] ||= []
      @group_by_set[e.set] ||= []  
      
      @group_by_set[e.set] << e
      @group_by_uid[e.uid] << e
      @group_by_layer[e.layer] << e
      
      
      #fill in the maps
      @layer_map[e.uid] = e.layer if @layer_map[e.uid].nil?
      @set_map[e.uid] ||= Set.new
      @set_map[e.uid] << e.set
    end

  end
  
  
  
end